<template>
  <div class="cylinderFlowControl-TabTrack">
    <el-table-form ref="form" :model="query">
      <el-form-item label="气瓶编号:" prop="xpbm">
        <el-input v-model.trim="query.gpbm" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="芯片编号:" prop="xpbm">
        <el-input v-model.trim="query.xpbm" placeholder="请输入" />
      </el-form-item>

      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="getData">查询</el-button>
      </template>
    </el-table-form>

    <div class="cylinderFlowControl-TabTrack-body">
      <baidu-map
        ref="map"
        :key="updateMap"
        :map-click="false"
        :enable-drawing-tool="true"
        scroll-wheel-zoom
        class="order_map"
        :center="'武汉'"
        :zoom="10"
        @ready="handler"
      >
        <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT" />
        <bm-info-window
          ref="infoWindowRef"
          :width="120"
          :offset="windowInfo.offset"
          :position="windowInfo.position"
          :show="windowInfo.show"
        >
          <div class="map-window" v-html="windowInfo.contents" />
        </bm-info-window>
        <bm-marker
          v-for="(item, index) in markers"
          :key="index"
          :position="item.point"
          :dragging="false"
          animation="BMAP_ANIMATION_BOUNCE"
          @click="actionMarker(index)"
        />
      </baidu-map>
      <div>
        <div v-if="showInfo" class="body-info">
          <div class="head">
            <span>气瓶历史踪迹</span>
            <i class="el-icon-d-arrow-right pointer" @click="expand" />
          </div>
          <el-timeline v-if="trackInfoData.length > 0">
            <el-timeline-item
              v-for="(item, index) in trackInfoData"
              :key="index"
              :timestamp="dateFormat(item.happendTime)"
              placement="top"
            >
              <i
                v-if="item.lng && item.lat"
                class="position el-icon-location pointer"
                @click="actionMarker(index)"
              />
              <div
                :class="{
                  bodyInfo_card: true,
                  first: index === 0,
                }"
              >
                <p class="card_title">{{ item.chipTraceTypeName }}</p>
                <template v-if="item.chipTraceType === 1 || item.chipTraceType === 9">
                  <p><span>装车机构：</span>{{ item.orgName }}</p>
                  <p><span>装车车辆：</span>{{ item.truckCode }}</p>
                  <p><span>装车人：</span>{{ item.ownerName }}</p>
                </template>
                <template v-else-if="item.chipTraceType === 2 || item.chipTraceType === 10">
                  <p><span>卸车机构：</span>{{ item.orgName }}</p>
                  <p><span>卸车车辆：</span>{{ item.truckCode }}</p>
                  <p><span>卸车人：</span>{{ item.ownerName }}</p>
                </template>

                <template v-else-if="item.chipTraceType === 3 || item.chipTraceType === 4">
                  <p>
                    <span>{{ item.chipTraceType === 3 ? "领瓶机构" : "还瓶机构" }}：</span>{{ item.orgName }}
                  </p>
                  <p v-if="item.ownerName"><span>还瓶人：</span>{{ item.ownerName }}</p>
                  <p v-if="item.truckCode"><span>配送车辆：</span>{{ item.truckCode }}</p>
                </template>
                <template v-else-if="item.chipTraceType === 11">
                  <p><span>充装场站：</span>{{ item.orgName }}</p>
                  <p><span>充装工位：</span>{{ item.ownerName }}</p>
                </template>
                <template v-else-if="item.chipTraceType === 22 || item.chipTraceType == 23">
                  <p><span>充装场站：</span>{{ item.orgName }}</p>
                  <p><span>检查人：</span>{{ item.ownerName }}</p>
                </template>
                <template v-else>
                  <p>
                    <span>客户名称：</span>{{ item.csmName }}
                    <span v-if="item.csmPhone">({{ item.csmPhone }})</span>
                  </p>
                  <p><span>地址：</span>{{ item.csmAddress }}</p>
                  <p>
                    <span>配送员：</span>{{ item.sender
                    }}<span v-if="item.orgName">({{ item.orgName }})</span>
                  </p>
                  <p v-if="item.sender && item.truckCode">
                    <span>配送车辆：</span>{{ item.truckCode }}
                  </p>
                </template>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
        <div v-else class="fold-div">
          <i class="el-icon-d-arrow-left pointer" @click="expand" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { queryTrackData, companySetting } from '@/api'
  import dayjs from 'dayjs'
  export default {
    name: 'TabTrack',
    data() {
      return {
        query: {
          gpbm: '',
          xpbm: ''
        },
        updateMap: 0,
        trackInfoData: [],
        isMapShow: true,
        showInfo: false,
        windowInfo: {
          show: false,
          contents: '',
          position: {}

        },
        markers: [],
        currentMarker: {
          lng: 0,
          lat: 0
        },
        BMap: null,
        map: null
      // redIcon = require('../../../assets/map_images/red_sprite.png')
      }
    },
    computed: {
      isShowInfo: {
        get: function() {
          return this.trackInfoData.length > 0
        },
        set: function(val) {
          this.showInfo = val
        }
      }
    },
    methods: {
      async handler({ BMap, map }) {
        this.map = map
        this.BMap = BMap
        const res = await companySetting()
        let currentCity = ''
        if (res.data.rows && res.data.rows.length > 0 && res.data.rows[0].city && res.data.rows[0].city !== '') currentCity = res.data.rows[0].city
        if (currentCity !== '') {
          map.centerAndZoom(currentCity, 14)
        } else {
          const localCity = new BMap.LocalCity()
          localCity.get(function(result) {
            const cityName = result.name
            map.centerAndZoom(cityName, 14)
          })
        }
      },
      dateFormat(val) {
        return val ? dayjs(val).format('YYYY-MM-DD HH:mm') : ''
      },
      getMapScript() {
        if (!window.BMap) {
          return new Promise((resolve, reject) => {
            const $script = document.createElement('script')
            global.document.body.appendChild($script)
            $script.src = `https://api.map.baidu.com/api?v=2.0&ak=${this.ak}&callback=_initBaiduMap`
            window._initBaiduMap = () => {
              resolve(window.BMap)
              global.document.body.removeChild($script)
            }
            $script.onerror = (e) => {
              reject()
              this.$message.error('百度地图控件加载失败，请检查网络并重试！')
            }
          })
        } else {
          return Promise.resolve(window.BMap)
        }
      },
      async getData() {
        this.markers = []
        const params = {
          ...this.query
        }
        if (!params.gpbm && !params.xpbm) {
          this.$message.error('请输入气瓶编码或者芯片编码！')
        }
        const { status, data } = await queryTrackData(params)
        if (status === 200) {
          if (data.length) {
            this.trackInfoData = data
            data.filter(item => item.lng && item.lat).forEach((v, i) => {
              const marker = this.addMarker(v, i)
              this.markers.push(marker)
            })

            // this.refreshMap()
          } else {
            this.$message.error('没有查到相关数据！')
          }
        }
        this.isShowInfo = true
      },
      refreshMap() {
        this.isMapShow = false
        this.$nextTick(() => {
          this.isMapShow = true
        })
      },
      addMarker(item, index) {
        const marpoint = new this.BMap.Point(item.lng, item.lat)
        const marker = new this.BMap.Marker(marpoint)
        marker.item = item
        this.map.addOverlay(marker)
        return marker
      },

      actionMarker(index) {
        if (this.markers[index]) {
          const allOverlay = this.map.getOverlays() // 获取所有标注点
          for (let i = 0; i < allOverlay.length; i++) {
            allOverlay[i].setAnimation() // 清除跳动动画
            if (allOverlay[i].point.lat === this.markers[index].point.lat && allOverlay[i].point.lng === this.markers[index].point.lng) {
              // eslint-disable-next-line no-undef
              allOverlay[i].setAnimation(BMAP_ANIMATION_BOUNCE) // 为当前点添加跳动动画
            }
          }
          this.openInfoWindow(this.markers[index].item, index)
          this.map.panTo(this.markers[index].point)
        }
      },
      openInfoWindow(item, index) {
        let content = ''
        if (item.chipTraceType === 5 || item.chipTraceType === 6) {
          content = `<div class="map-window"><p><span>联系人：</span><span>${item.contact}</span></p><p><span>电话：</span><span>${item.csmPhone}</span></p><p><span>地址：</span><span>${item.csmAddress}</span></p><p><span>时间：</span><span>${dayjs(item.happendTime).format('YYYY-MM-DD HH:MM')}</span></p><p><span>配送员：</span><span>${item.sender}</span></p></div>`
        } else if (item.chipTraceType === 3) {
          content = `<div class="gasTank-info"><p><span>领瓶机构：</span><span>${item.orgName}</span></p><p><span>领瓶人：</span><span>${item.ownerName}</span></p></div>`
        } else if (item.chipTraceType === 4) {
          content = `<div class="gasTank-info"><p><span>还瓶机构：</span><span>${item.orgName}</span></p><p><span>还瓶人：</span><span>${item.ownerName}</span></p></div>`
        }
        this.windowInfo.contents = content
        this.windowInfo.position = this.markers[index].point
        this.windowInfo.offset = new this.BMap.Size(0, -40)
        this.windowInfo.show = true
      },
      expand() {
        this.showInfo = !this.showInfo
      }
    }
  }
</script>

<style lang="scss" scoped>
.cylinderFlowControl-TabTrack {
  height: 100%;
  .cylinderFlowControl-TabTrack-body {
    display: flex;
    height: calc(100% - 61px);
    .order_map {
      height: 100%;
      flex: 1;
    }
    .body-info {
      width: 368px;
      height: 100%;
      margin-left: 5px;
      overflow-y: auto;
      border: 1px solid #ebeff6;
    }
    .fold-div {
      width: 20px;
      text-align: center;
    }
    .head {
      display: flex;
      justify-content: space-between;
      padding: 5px;
      font-size: 14px;
      font-weight: bold;
      color: rgb(119, 119, 119);
      border-bottom: 1px solid #ebeff6;
    }
    /deep/.el-timeline {
      margin-top: 20px;
      margin-left: 120px;

      .el-timeline-item__content {
        position: relative;
      }

      .position {
        position: absolute;
        top: -25px;
        left: 120px;
        width: 20px;
        height: 20px;
        font-size: 20px;
        color: green;
      }

      .bodyInfo_card {
        .card_title {
          position: absolute;
          top: -23px;
          left: -120px;
          max-width: 120px;
          font-size: 14px;
          font-weight: 700;
        }

        p {
          line-height: 20px;
        }
      }
      .first {
        color: crimson;
      }
    }
  }
}
</style>
